package com.cleverest.cleverestdiary.controller;

import com.cleverest.cleverestdiary.pojo.Result;
import com.cleverest.cleverestdiary.pojo.ScheduleCategory;
import com.cleverest.cleverestdiary.service.ScheduleCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/schedule-category")
public class ScheduleCategoryController {

    @Autowired
    private ScheduleCategoryService scheduleCategoryService;

    /**
     * 新增日程分类
     *
     * @param scheduleCategory 日程分类对象
     * @return 操作结果
     */
    @PostMapping
    public Result add(@RequestBody @Validated(ScheduleCategory.Add.class) ScheduleCategory scheduleCategory) {
        //查询日程分类
        ScheduleCategory ac = scheduleCategoryService.findByScheduleCategoryName(scheduleCategory.getCategoryName());
        if (ac == null) {
            //没有重名
            scheduleCategoryService.add(scheduleCategory);
            return Result.success();
        } else {
            //占用
            return Result.error("已经存在该日程分类名");
        }
    }

    /**
     * 查询所有日程分类
     *
     * @return 日程分类列表
     */
    @GetMapping
    public Result<List<ScheduleCategory>> list() {
        List<ScheduleCategory> scheduleCategories = scheduleCategoryService.list();
        return Result.success(scheduleCategories);
    }

    /**
     * 根据id查询日程分类详情
     *
     * @param id 日程分类id
     * @return 日程分类详情
     */
    @GetMapping("/detail")
    public Result<ScheduleCategory> detail(@RequestParam Integer id) {
        ScheduleCategory scheduleCategory = scheduleCategoryService.findById(id);
        return Result.success(scheduleCategory);
    }

    /**
     * 更新日程分类
     *
     * @param scheduleCategory 日程分类对象
     * @return 操作结果
     */
    @PutMapping
    public Result update(@RequestBody @Validated(ScheduleCategory.Update.class) ScheduleCategory scheduleCategory) {
        scheduleCategoryService.update(scheduleCategory);
        return Result.success();
    }

    /**
     * 删除日程分类
     *
     * @param id 日程分类id
     * @return 操作结果
     */
    @DeleteMapping
    public Result delete(@RequestParam Integer id) {
        ScheduleCategory scheduleCategory = scheduleCategoryService.findById(id);
        if (scheduleCategory == null) {
            return Result.error("找不到这个日程分类");
        } else {
            scheduleCategoryService.delete(id);
        }
        return Result.success();
    }
}